var common = require('../../../../utils/common.js');
var app = getApp();
Page({
  data: {
    searchValue: "",
    showDelete: false,
    result: {subjects:[]},
    showMore: true,
    page: 0
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    //this.handleSearchData('top250');
  },
  onShow: function () {
    // 页面显示
  },

  //上滑加载更多
  onReachBottom: function () {
    var _this = this;
    if (_this.data.showMore) {
      _this.handleSearchData(_this.data.searchValue);
    }
  },
  /** 搜索影视 */
  bindSearchInput: function (event) {
    var value = event.detail.value;
    var readyData = { showDelete: false, page: 0, searchValue: value};
    if (value.length > 0) {
      readyData = { showDelete: true, page: 0, searchValue: value}; 
      this.handleSearchData(value);
    }else{
      this.setData({ result: { subjects: []}});
    }
    this.setData(readyData);
  },
  /**清空输入框 */
  bindSearchDelete: function (event) {
    var readyData = { searchValue: "", showDelete: false, result: { subjects: []}, page:0 };
    this.setData(readyData);
  },
  /**点击取消 */
  bindSearchCancel: function (event) {
    wx.navigateBack();
  },
  /** 提交搜索请求 */
  handleSearchData: function (value) {
    var that = this;
    common.dataLoading("加载中", "loading");
    var serchURL = app.globalData.doubanBase + app.globalData.search + value + "&start=" + that.data.page*10;
    wx.request({
      url: serchURL,
      method: 'GET',
      header: { 'content-type': 'json' },
      success: function (res) {
        // success
        var data = res.data;
        that.processSearchData(data);
        that.setData({page: ++that.data.page});
      }
    });
  },
  /**组装搜索数据 */
  processSearchData: function (data) {
    var movies = [];
    for (let idx in data.subjects) {
      var subject = data.subjects[idx];
      var directors = "";
      var separate = " / ";
      for (let i in subject.directors) {
        directors += subject.directors[i].name + separate;
      }
      directors = directors.substring(0, directors.length - separate.length);
      var summary = subject.rating.average + "分" + separate + subject.year + separate + directors;
      var temp = {
        id: subject.id,
        casts: subject.casts,
        collect_count: subject.collect_count,
        directors: subject.directors,
        title: subject.title,
        images: subject.images,
        rating: subject.rating,
        year: subject.year,
        summary: summary
      };
      movies.push(temp);
    }
    var readyData = {};
    readyData["result"] = {
      subjects: this.data.result.subjects.concat(movies)
    }
    this.setData(readyData);
  },
  /** 点击进入搜索条目 */
  handletap: function (event) {
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/my/movie/movie-detail/movie-detail?id=' + id
    })
  }
})